package com.zzzy.cont.service.mycon;

import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.FileUtil;
import com.zzzy.cont.common.enums.ConStatusEnum;
import com.zzzy.cont.dao.entity.ConFile;
import com.zzzy.cont.dao.entity.Contract;
import com.zzzy.framework.common.enums.sys.UserStatusEnum;
import com.zzzy.framework.common.util.SecurityUtils;
import com.zzzy.sys.dto.UserInfoDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class MyConAuditService extends MyConService {

    @Transactional
    public void applyAudit(Long id, Long userId) {
        Contract contract = getConByIdForUpdate(id);
        AssertUtil.isEquals(ConStatusEnum.AUDIT.getValue(), contract.getStatus(), "合同状态错误，无法申请审核");
        Long loginUserId = SecurityUtils.getLoginUser().getId();
        AssertUtil.isNotEquals(userId, loginUserId, "选择的用户不能 为当前用户");
        AssertUtil.isTrue(userService.hasPermission(userId, "con:process:audit"), "选择的用户无审核权限，如有疑问，请联系管理员");
        UserInfoDto userInfoDto = userService.getUserInfoById(userId);
        AssertUtil.isEquals(UserStatusEnum.ENABLE.getValue(), userInfoDto.getStatus(), "选择的用户状态错误，无法申请审核，如有疑问，请联系管理员");
        contract.setUpdateTime(LocalDateTime.now());
        contract.setOperatorId(userId);
        contract.setOperatorName(userInfoDto.getNickName());
        baseMapper.updateById(contract);

        //添加合同动态
        conActivityNoteService.addSysNote(id, "申请审核至 " + userInfoDto.getNickName());

        String message = contract.getTradeCompany() +" - "+ contract.getName()  + " 待审核";
        conNotifyMessageService.addNotifyMessage(id, userId, message);
    }

    @Transactional
    public void auditComplete(Long id) {
        Contract contract = getConByIdForUpdate(id);
        AssertUtil.isEquals(ConStatusEnum.AUDIT.getValue(), contract.getStatus(), "合同状态错误，无法进入签订阶段");
        ConFile conFile = conFileService.getConFileByConId(id);
        AssertUtil.nonNull(conFile.getPdfFileBlob(), "合同文件 未转换PDF格式");
        contract.setStatus(ConStatusEnum.SIGN.getValue());
        contract.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(contract);
        conFileHistoryService.addAuditedHistory(id);
        conFileHistoryService.addSigningHistory(id);
        //添加合同动态
        conActivityNoteService.addSysNote(id, "审核完毕，合同进入签订中");
    }

    /**
     * 审核并保存pdf格式文件
     */
    @Transactional
    public void auditWithSavePdf(Long id, byte[] byteArray) {
        AssertUtil.isTrue(FileUtil.checkIsPDF(byteArray), "文件非PDF格式，无法保存");
        conFileService.updatePdfByConId(id, byteArray);
        auditComplete(id);
    }

}
